import { Component, EventEmitter, Input, OnInit, Output, TemplateRef, ViewChild } from '@angular/core';
import { MessagerService } from '@farris/ui-messager';
import { NotifyService } from '@farris/ui-notify';
import { cloneDeep } from 'lodash-es';
import { BsModalRef, BsModalService } from '@farris/ui-modal';
import { DomService } from '@farris/designer-services';
import { MultiViewManageService } from '../../services/multi-view-manage.service';
import { MultiViewItemProp } from '../../multi-view-item-property-config';
import { DgControl } from '../../../../../../utils/dg-control';

@Component({
  selector: 'app-multi-view-editor',
  templateUrl: './multi-view-editor.component.html',
  styleUrls: ['./multi-view-editor.component.css']
})
export class MultiViewEditorComponent implements OnInit {

  @Output() closeModal = new EventEmitter<any>();
  @Output() submitModal = new EventEmitter<any>();
  @Input() value;
  @Input() editorParams = { dataSource: '', multiContainerViewModelId: '' };
  @ViewChild('footer') modalFooter: TemplateRef<any>;
  modalConfig = {
    title: '多视图编辑器',
    width: 700,
    height: 600,
    showButtons: true
  };

  /**
   * 属性面板相关
   */
  propertyConfig;
  propertyData;
  showPropertyPanel = false;

  /** 当前所有的视图数组 */
  viewItems = [];
  /** 选择的视图 */
  selectedItem;

  /** 新增视图类型选择模板 */
  @ViewChild('viewTypeTmpl') viewTypeTmpl: TemplateRef<any>;

  /** 新增视图类型选择按钮模板 */
  @ViewChild('viewTypeBtnTmpl') viewTypeBtnTmpl: TemplateRef<any>;

  /** 新增视图类型选择窗口实例 */
  newViewModelRef: BsModalRef;

  /** 支持的视图类型 */
  viewTypeOptions;

  /** 选择的视图类型 */
  selectedViewType = 'ListView';

  constructor(
    private notifyService: NotifyService,
    private msgService: MessagerService,
    private modalService: BsModalService,
    private domService: DomService,
    private itemManageService: MultiViewManageService

  ) { }

  ngOnInit() {
    if (this.value && this.value.length > 0) {
      this.viewItems = cloneDeep(this.value);
    }
    this.itemManageService.initViewTypes(this.editorParams.dataSource, this.viewItems);

    this.viewTypeOptions = this.itemManageService.viewTypeOptions;
  }


  changeSelectedView(item: any) {
    this.selectedItem = item;
    // 属性面板
    const multiViewItemProp = new MultiViewItemProp();
    this.propertyConfig = multiViewItemProp.getPropertyConfig();
    this.propertyData = item;
    this.showPropertyPanel = true;
  }


  /**
   * 新增节点
   * @param type 节点类型
   */
  addItem() {

    this.newViewModelRef = this.modalService.show(this.viewTypeTmpl, {
      title: '新增视图',
      width: 400,
      height: 200,
      showButtons: true,
      buttons: this.viewTypeBtnTmpl,
      showMaxButton: false
    });

  }
  cancelNewView() {
    this.newViewModelRef.close();
  }

  confirmNewView() {

    this.itemManageService.createMultiViewItem(this.selectedViewType, this.viewItems).subscribe(viewItem => {
      if (viewItem) {
        this.viewItems.push(viewItem);
      }
      this.newViewModelRef.close();

    });


  }

  removeItem() {
    if (!this.selectedItem) {
      this.notifyService.warning('请先选择要删除的视图');
      return;
    }

    this.msgService.question('确认删除【' + this.selectedItem.title + '】节点?', () => {
      const index = this.viewItems.findIndex(item => item.id === this.selectedItem.id);

      this.viewItems.splice(index, 1);


      // 从待追加组件中移除
      this.itemManageService.removeItem(this.selectedItem);

      // 从记录的新增交叉表视图中移除
      if (this.selectedItem.viewType === 'CrosstabView' && this.itemManageService.newCrosstabViewIds.includes(this.selectedItem.id)) {
        this.itemManageService.newCrosstabViewIds = this.itemManageService.newCrosstabViewIds.filter(id => id !== this.selectedItem.id);
      }

      this.selectedItem = null;

      this.showPropertyPanel = false;

    });

  }

  moveUpItem() {

    if (!this.selectedItem) {
      this.notifyService.warning('请先选择要移动的视图');
      return;
    }

    const index = this.viewItems.findIndex(item => item.id === this.selectedItem.id);
    if (index === 0) {
      return;
    }
    this.viewItems.splice(index, 1);
    this.viewItems.splice(index - 1, 0, this.selectedItem);

  }

  moveDownItem() {


    if (!this.selectedItem) {
      this.notifyService.warning('请先选择要移动的视图');
      return;
    }

    const index = this.viewItems.findIndex(item => item.id === this.selectedItem.id);

    if (index === this.viewItems.length - 1) {
      return;
    }
    this.viewItems.splice(index, 1);
    this.viewItems.splice(index + 1, 0, this.selectedItem);

  }

  /**
   * 取消
   */
  clickCancel() {
    this.closeModal.emit();
  }

  /**
   * 确定
   */
  clickConfirm() {
    // 向DOM中添加Component和ViewModel 节点
    Object.keys(this.itemManageService.createdComponent).forEach(componentId => {
      const { component, viewModel } = this.itemManageService.createdComponent[componentId];
      this.domService.addComponent(component);
      this.domService.addViewModel(viewModel);
    });

    // 移除视图后，要同步删除dom中已有的component和viewModel，以及可能有的外部组件声明和订阅
    if (this.value && this.value.length) {
      this.value.forEach(oldItem => {
        // 被删除的视图
        if (!this.viewItems.find(newItem => newItem.id === oldItem.id)) {
          const cmpRef = this.domService.selectNode(oldItem, item => item.type === DgControl.ComponentRef.type);
          if (cmpRef) {
            const cmp = this.domService.getComponentById(cmpRef.component);
            if (cmp) {
              this.domService.deleteComponent(cmpRef.component);
              this.domService.deleteViewModelById(cmp.viewModel);
            }
          }
        }
      });
    }

    this.submitModal.emit({ value: this.viewItems });


  }
}
